package com.echo.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.echo.entity.bean.CommonResult;
import com.echo.entity.bean.VerifyCode;
import com.echo.entity.dto.*;
import com.echo.entity.pojo.User;
import com.echo.exception.VerifyException;
import com.echo.service.impl.MailServiceImpl;
import com.echo.service.impl.UserServiceImpl;
import com.echo.utils.VerifyCodeUtil;
import javafx.scene.image.Image;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
//用户登陆注册控制类
public class UserAccountController {
    private UserServiceImpl userService;
    private RedisTemplate redisTemplate;
    private MailServiceImpl mailService;
    private VerifyCodeUtil verifyCodeUtil;

    public UserAccountController(UserServiceImpl userService, RedisTemplate redisTemplate, MailServiceImpl mailService, VerifyCodeUtil verifyCodeUtil) {
        this.userService = userService;
        this.redisTemplate = redisTemplate;
        this.mailService = mailService;
        this.verifyCodeUtil = verifyCodeUtil;
    }


    //用户注册
    @PostMapping("/register")
    public CommonResult<String> userRegister(@RequestBody UserRegisterDTO userRegisterDTO){
        //检验验证码
        if (null==redisTemplate.opsForValue().get("mvc_"+userRegisterDTO.getVerifyCode())){
            throw new VerifyException("验证码错误");
        }
        //注册
        userService.userRegister(userRegisterDTO);
        return new CommonResult<>(20000,"OK","注册成功");
    }

    //用户登录
    @PostMapping("/login")
    public CommonResult<String> userLogin(@RequestBody UserLoginDTO userLoginDTO){
        //检验验证码
        if (null==redisTemplate.opsForValue().get("mvc_"+userLoginDTO.getVerifyCode())){
            throw new VerifyException("验证码错误");
        }
        //登录
        String token = userService.userLogin(userLoginDTO);
        return new CommonResult<>(20000,"OK",token);
    }

    /**
     * 获取验证码
     * 该验证码用于发送邮箱验证码之前的验证
     * @param response
     * @throws IOException
     */
    @PostMapping("/verifyCode")
    public void verifyCode(HttpServletResponse response) throws IOException {
        //设置长宽
        VerifyCode verifyCode = verifyCodeUtil.generate(80, 28);
        String code = verifyCode.getCode();
        System.out.println(code);
        //将VerifyCode写入redis
        redisTemplate.opsForValue().set("vc_" + code, "1", 300, TimeUnit.SECONDS);
        //设置响应头
        response.setHeader("Pragma", "no-cache");
        //设置响应头
        response.setHeader("Cache-Control", "no-cache");
        //在代理服务器端防止缓冲
        response.setDateHeader("Expires", 0);
        //设置响应内容类型
        response.setContentType("image/jpeg");
        response.getOutputStream().write(verifyCode.getImgBytes());
        response.getOutputStream().flush();
    }

    /**
     * 用户修改个人信息
     * 可修改用户名，密码
     * @param userUpdateDTO
     * @param request
     * @return
     */
    @PostMapping("/info/update")
    public CommonResult<String> updatePersonalInfo(@RequestBody UserUpdateDTO userUpdateDTO, HttpServletRequest request){
        userService.updatePersonalInfo(userUpdateDTO,(Integer) request.getAttribute("uid"));
        return new CommonResult<>(20000,"OK","更新成功");
    }


    /**
     * 更新用户头像url
     * @param avatar
     * @param request
     * @return
     */
    @PostMapping("/avatar/update")
    public CommonResult<String> updatePersonalAvatar(String avatar,HttpServletRequest request){
        UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
        userUpdateWrapper.eq("id",(Integer)request.getAttribute("uid")).set("avatar",avatar);
        userService.update(userUpdateWrapper);
        return new CommonResult<>(20000,"OK","更新成功");
    }

    //用户注销
    //需要输入用户名、密码和验证码
    public CommonResult<String> destroyAccount(@RequestBody UserDestroyAccountDTO userDestroyAccountDTO,HttpServletRequest request){
        //检验验证码
        if (null==redisTemplate.opsForValue().get("mvc_"+userDestroyAccountDTO.getVerifyCode())){
            throw new VerifyException("验证码错误");
        }
        userService.destroyAccount(userDestroyAccountDTO,(Integer) request.getAttribute("uid"));
        return new CommonResult<>(20000,"OK","注销成功");
    }

    /**
     * 发送邮箱验证码
     * @param verifyCodeMailGetDTO 邮箱地址与验证码（需要先获取第一个验证码才能获取邮箱验证码）
     * @return
     * @throws Exception
     */
     @PostMapping("/mail-verify-code")
    public CommonResult<String> getMailVerifyCode(@RequestBody VerifyCodeMailGetDTO verifyCodeMailGetDTO) throws Exception {
         System.out.println(redisTemplate.opsForValue().get("vc_"+verifyCodeMailGetDTO.getVerifyCode()));
         //检验第一个非邮箱验证码
         if (null==redisTemplate.opsForValue().get("vc_"+verifyCodeMailGetDTO.getVerifyCode())){
             throw new VerifyException("验证码错误");
         }


        //生成验证码
        // 设置长宽
        VerifyCode verifyCode = verifyCodeUtil.generate(80, 28);
        //放入redis
        String code = verifyCode.getCode();
        //将VerifyCode写入redis
        redisTemplate.opsForValue().set("mvc_" + code, "1", 300, TimeUnit.SECONDS);

        //将验证码图片编码成base64的形式，方便在thymelef中显示
        byte[] verifyImageBytes = verifyCode.getImgBytes();
        BASE64Encoder encoder = new BASE64Encoder();
         System.out.println(encoder.encode(verifyImageBytes));
         String verifyImageHtml = new String("data:image/jpeg;base64,"+encoder.encode(verifyImageBytes) );

         //发送邮箱验证信件
         try {
             mailService.sendVerifyCodeMail(verifyCodeMailGetDTO.getMail(),verifyImageHtml);
         } catch (Exception e) {
             e.printStackTrace();
             throw e;
         }
         return new CommonResult<>(20000,"OK","邮件已发送");
    }
}
